package com.lg.atp.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.util.ImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ImageBanner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.lg.atp.common.Constants;
import com.lg.atp.entity.TblAppInfo;
import com.lg.atp.entity.TblControls;
import com.lg.atp.entity.TblDeviceInfo;
import com.lg.atp.service.IAppInfoService;
import com.lg.atp.service.IControlService;
import com.lg.atp.service.IDeviceInfoService;
import com.lg.atp.utils.DeviceConstants;
import com.lg.atp.utils.PictureTool;
import com.lg.atp.vo.device.DeviceInfoVo;
import com.lg.atp.ws.WSClient;

@RestController
@RequestMapping("obj")
public class ObjectTreeController {
	
	private Log log = LogFactory.getLog(ObjectTreeController.class);
	
	@Autowired
	private IControlService iControlService;
	@Autowired
	private IAppInfoService iAppInfoService;
	@Autowired
	private IDeviceInfoService iDeviceInfoService;
	private @Value("${targetFilePath}") String targetFilePath;
	private @Value("${relibleMaster}") String relibleMaster;
	private @Value("${serverURL}") String serverURL;
	
	@GetMapping("toObjectTree")
	public ModelAndView toObjectTree() {
		ModelAndView model = new ModelAndView();
		List<TblAppInfo> applist = iAppInfoService.selectEditedApp();
		model.addObject("applist", applist);
		model.setViewName("objectTree");
		return  model;
	}
	
	
	@GetMapping("toDeviceChoose")
	public ModelAndView toDeviceChoose() {
		
		ModelAndView model = new ModelAndView();
		model.setViewName("chooseDevice");	
		return model;
	}
	@PostMapping("getDeviceList")
	public Map<String,Object> getDeviceList(Integer start,Integer limit) {
		
		//ModelAndView model = new ModelAndView();
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			iDeviceInfoService.saveDeviceList4Macaca();
			PageInfo<TblDeviceInfo> deviceList = iDeviceInfoService.getDeviceListCanbeUsed(start,limit);
			result.put("data", deviceList);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取设备失败："+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "获取设备失败");
		}
		
		
		return result;
	}
	@PostMapping("jcroppictrueForAjax")
	public Map<String,Object> jcroppictrueForAjax(Integer startX,Integer startY,Integer width,Integer height,String pictureBase64Data) {
		
		//ModelAndView model = new ModelAndView();
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			String sourceFilePath = targetFilePath+"temp/"+UUID.randomUUID()+".jpg";
			String targetFile = targetFilePath+"temp/"+UUID.randomUUID()+".jpg";
			PictureTool.GenerateImage(pictureBase64Data, sourceFilePath);
			File fileOne = new File(sourceFilePath);
		     BufferedImage imageFirst = ImageIO.read(fileOne);
		     float bill = ((float)(imageFirst.getHeight())/(float)500);
		     imageFirst=PictureTool.crop(imageFirst, (int)(startX*bill), (int)(startY*bill), (int)(width*bill), (int)(height*bill));
			File outFile = new File(targetFile);
		    ImageIO.write(imageFirst, "jpg", outFile);// 写图片
		    String afterBase64 = PictureTool.GetImageStr(targetFile);
			result.put("data", afterBase64);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("截图失败："+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "截图失败");
		}
		
		
		return result;
	}
	@PostMapping("recorddevice")
	public Map<String,Object> recorddevice( Long deviceId) {
		
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			TblDeviceInfo tblDeviceInfo ;
			synchronized (ObjectTreeController.class) {
				iDeviceInfoService.saveDeviceList4Macaca();
				tblDeviceInfo = iDeviceInfoService.geTblDeviceInfoById(deviceId);
				if (!DeviceConstants.DEVICE_STATUS_VALID.equals(tblDeviceInfo.getDeviceStatus())) {
					result.put("status", Constants.RETURN_FAIL);
					result.put("errorMsg", "当前设备不可用");
					return result;
				}
				
			}
			tblDeviceInfo.setDeviceStatus(DeviceConstants.DEVICE_STATUS_USING);
			iDeviceInfoService.updateDevice(tblDeviceInfo);
			if(!"ios".equals(tblDeviceInfo.getPlatform())) {
				WSClient client = new WSClient(relibleMaster);
				String webSocketPortAndSourcePort = client.controlDevicesById(tblDeviceInfo.getUdid(),"record");
				String[] ports = webSocketPortAndSourcePort.split(":");
				DeviceInfoVo device = new DeviceInfoVo();
				device.setScreenHeight(tblDeviceInfo.getScreenHeight());
				device.setScreenWidth(tblDeviceInfo.getScreenWidth());
				device.setSlaveIp(tblDeviceInfo.getSlaveIp());
				device.setWebSocketPort(ports[0]);
				device.setSourcePort(ports[1]);
				result.put("serverURL", serverURL);
				result.put("data", device);
			}
		}catch(Exception e) {
			e.printStackTrace();
			log.error("启动设备失败："+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "启动设备失败");
		}
		return result;
	}
	
	@PostMapping("loadData")
	public Map<String,Object> loadObjectTreeData( Long appId){
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			List<TblControls> controlTree = iControlService.selectRootControl(appId);
			result.put("data",controlTree);
		}catch(Exception e) {
			e.printStackTrace();
			log.error("加载控件树失败："+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "加载控件树失败");
		}
		return result;
	}
	
	
	@PostMapping("query")
	public Map<String,Object> loadObjectTreeByParam(Long appId,String param){
		
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("appId", appId);
		    map.put("param", param);
		    List<TblControls> controlTree = new ArrayList<TblControls>(); 
		    if(StringUtils.isBlank(param))
		    	controlTree = iControlService.selectRootControl(appId);
		    else
		    	controlTree = iControlService.selectControlByParam(map);
			result.put("data",controlTree);
		}catch(Exception e) {
			e.printStackTrace();
			log.error("查询控件失败："+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "查询控件失败");
		}
		return result;
	}
	
	@PostMapping("getObjectTreeByParamWithState")
    public Map<String,Object> getObjectTreeByParamWithState(Long appId,String param,String types,String locateTypes){
		
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("appId", appId);
		    map.put("param", param);
		    map.put("typeStr", types);
		    map.put("locateTypes", locateTypes);
		    List<TblControls> controlTree = iControlService.selectControlByParamWithState(map);
			result.put("data",controlTree);
		}catch(Exception e) {
			e.printStackTrace();
			log.error("获取控件失败："+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "获取控件失败");
		}
		return result;
	}
	
	@PostMapping("saveNode")
	public Map<String,Object> addObjectTreeNode(TblControls node){
		
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			Long id = node.getId();
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("controlName", node.getControlName());
			map.put("parentId", node.getParentId());
			map.put("id", id);
			map.put("appId", node.getAppId());
			Long count = iControlService.selectControlByName(map);
			if(count > 0) {
				result.put("status", Constants.RETURN_FAIL);
				result.put("errorMsg", "已经存在相同名称的兄弟节点,请重新输入名称");
				return result;
			}
			if(id == null) {
				TblControls control = iControlService.saveControl(node);
				result.put("data", control);
			}
			else {
				List<TblControls> controls = iControlService.updateControl(node);
				result.put("data", controls);
			}
				 
			
		}catch(Exception e) {
			e.printStackTrace();
			log.error("新增控件失败："+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "新增控件失败");
		}
		return result;
	}
	
	

	
	@PostMapping("getObjectNode")
	public Map<String,Object> getObjectNode( Long controlId){
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			TblControls controlNode = iControlService.selectControlById(controlId);
			result.put("data",controlNode);
		}catch(Exception e) {
			e.printStackTrace();
			log.error("加载控件树失败："+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "加载控件树失败");
		}
		return result;
	}
	
	
	@PostMapping("delObjectNode")
	public Map<String,Object> delObjectNode( Long controlId){
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			iControlService.delControl(controlId);
		}catch(Exception e) {
			e.printStackTrace();
			log.error("删除控件树失败："+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "删除控件树失败");
		}
		return result;
	}
	
	@PostMapping("changeControlParent")
	public Map<String,Object> changeControlParent(Long id,Long parentId){
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			iControlService.changeControlParent(id,parentId);
		}catch(Exception e) {
			e.printStackTrace();
			log.error("拖拽控件失败："+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "拖拽控件失败:"+e.getMessage());
		}
		return result;
	}
	
	@PostMapping("setControlToRoot")
	public Map<String,Object> setControlToRoot(Long id){
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("status", Constants.RETURN_SUCCESS);
		try {
			iControlService.setControlToRoot(id);
			
		}catch(Exception e) {
			e.printStackTrace();
			log.error("设置根节点失败："+e.getMessage());
			result.put("status", Constants.RETURN_FAIL);
			result.put("errorMsg", "设置根节点失败:"+e.getMessage());
		}
		return result;
	}
}
